<template>
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    title="采集参数选择"
    style="min-width: 1200px"
    draggable
    @close="closeDialog"
    destroy-on-close
  >
    <div class="search-container">
      <el-form :model="formData" :inline="true">
        <el-form-item label="生产设备">
          <el-input
            v-model="props.equipName"
            placeholder="生产设备"
            clearable
            :disabled="true"
          />
        </el-form-item>
        <el-form-item label="设备类型" prop="equipCode">
          <el-select
            v-model="formData.equipTypeId"
            placeholder="请选择设备类型"
            clearable
            @change="changeEquipType"
          >
            <el-option
              v-for="item in equipTypeList"
              :key="item.equipTypeId"
              :label="`${item.equipTypeCode}`"
              :value="item.equipTypeId"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item> -->
      </el-form>
    </div>
    <el-card shadow="never" class="table-container">
      <div class="formTable3">
        <el-table
          ref="singleTableRef"
          v-loading="laodingTable"
          :data="tableData"
          highlight-current-row
          border
          @selection-change="handleCurrentChange1"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column
            label="参数名"
            prop="parameterName"
            min-width="120"
            show-overflow-tooltip
            sortable
          />

          <el-table-column
            label="参数描述"
            prop="parameterDesc"
            min-width="120"
            show-overflow-tooltip
          />
          <el-table-column
            label="数据类型"
            prop="parameterType"
            min-width="120"
            align="center"
            show-overflow-tooltip
            sortable
          >
            <template #default="scope">
              {{ useDictionary("ScaDataType", scope.row.parameterType) }}
            </template>
          </el-table-column>
          <el-table-column
            label="采集方式"
            prop="collectionFrequency"
            min-width="120"
            align="center"
            show-overflow-tooltip
            sortable
          >
            <template #default="scope">
              {{
                useDictionary(
                  "ScaCollectFrequency",
                  scope.row.collectionFrequency
                )
              }}
            </template>
          </el-table-column>
          <el-table-column
            label="采集频率"
            prop="collectionFrequencyTime"
            min-width="120"
            align="center"
            show-overflow-tooltip
            sortable
          >
            <template #default="scope">
              <span v-if="scope.row.collectionFrequencyTime">
                {{ scope.row.collectionFrequencyTime
                }}{{
                  scope.row.collectionFrequencyUnit === "s"
                    ? "秒"
                    : scope.row.collectionFrequencyUnit === "m"
                    ? "分钟"
                    : ""
                }}
              </span>
              <span v-else></span>
            </template>
          </el-table-column>
          <el-table-column
            label="参数类别"
            prop="paramType"
            min-width="120"
            align="center"
            show-overflow-tooltip
            sortable
          >
            <template #default="scope">
              {{ useDictionary("ScaParamType", scope.row.paramType) }}
            </template>
          </el-table-column>

          <el-table-column
            label="计量单位"
            prop="measurementUnit"
            min-width="120"
            align="center"
            show-overflow-tooltip
            sortable
          />
          <el-table-column
            label="显示方式"
            prop="showType"
            align="center"
            min-width="120"
            show-overflow-tooltip
            sortable
          >
            <template #default="scope">
              {{ useDictionary("ScaShowType", scope.row.showType) }}
            </template>
          </el-table-column>
          <el-table-column
            label="序号"
            align="center"
            prop="sort"
            min-width="120"
            show-overflow-tooltip
            sortable
          />
          <el-table-column
            label="地址"
            prop="url"
            min-width="120"
            show-overflow-tooltip
            sortable
          />
          <el-table-column
            label="备注"
            prop="remarks"
            min-width="100"
            show-overflow-tooltip
          />
        </el-table>
      </div>
    </el-card>
    <!-- <el-pagination
      :background="true"
      :current-page="pageable.pageNum"
      :page-size="pageable.pageSize"
      :page-sizes="[5, 10, 15, 20]"
      :total="pageable.total"
      layout="total, sizes, prev, pager, next, jumper"
      class="mt-[20px]"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    /> -->
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" :loading="loading" @click="handleSubmit"
          >确 定
        </el-button>
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { useTable, useDictionary } from "@/utils/useTable";
import { ElMessage, ElForm } from "element-plus";
import { ref, reactive, watch, onBeforeUnmount } from "vue";
import request from "@/utils/request";
import dayjs from "dayjs";
import { server } from "typescript";
defineOptions({
  name: "PSMPARAMMONITORRULESELECT",
  inheritAttrs: false,
});

const emit = defineEmits(["change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  equipId: {
    type: String,
    default: () => {
      return "";
    },
  },
  equipName: {
    type: String,
    default: () => {
      return "";
    },
  },
  breakList: {
    type: Object,
    default: () => {
      return {};
    },
  },
});

const tableData = ref([]);

//获取表格数据 api 方法
const requestApi = "/iotadmin/scaequipinfo/queryByPage";
//获取数据初始化参数
const initParam = {};
// 初始化搜索参数数据
// 初始化搜索参数数据
const searchParamInit = {};
// 是否需要分页
const pagination = true;
// 无需二次数据处理&不传赞数也行
const tableData1 = ref([]);
const dataCallBack = (data: any) => {
  // data.forEach((item: any, index: number) => {
  // });
  // if (data) {
  //   data = data.filter(function (value, index, arr) {
  //     return value.assetStatus == "3";
  //   });
  // }
  return data;
};
// const dataCallBack = ref(undefined);
// 数据请求错误后处理
function requestError() {}
//删除
const deleteParam = {
  api: "",
  data: {},
};

const formData = reactive({
  equipTypeId: "",
});

const {
  ids,
  searchParam,

  handleSizeChange,
  handleSelectionChange,
  handleTableDelete,
  handleCurrentChange,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack,
  requestError,
  deleteParam
);

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    // 获取设备类型列表
    getEquipTypeList();
    // breakSingleTableSelect();
  }
);

// 选择高亮
const singleTableRef = ref();
const currentRow = ref();
const handleCurrentChange1 = (val: any) => {
  console.log("选中的", val);

  currentRow.value = val;
};

// 回显时设置选项
const breakSingleTableSelect = () => {
  console.log("返回的数据", props.breakList);
  console.log("表格数据", tableData.value);

  //定义了一个空数组
  let checkedrow: any = [];
  //循环列表所有的数据
  tableData.value.forEach((item) => {
    //循环后台返回需要打钩的数据
    props.breakList.forEach((v) => {
      //这就是个条件  根据自己的条件去写
      if (item.id == v.id) {
        //给空数组里面添加我需要回显打钩的数据
        checkedrow.push(item); // 相等添加到空数组中
      }
    });
  });
  //最主要的就是这个方法这个方法在dom渲染完会去回调
  nextTick(() => {
    //遍历回显数组
    checkedrow.forEach((row) => {
      //singleTableRef这个是在table上面加的ref的值  通过它的属性方法去看那几个属性打钩
      singleTableRef.value.toggleRowSelection(row, true); // 回显
    });
  });
};
/** 关闭表单弹窗 */
function closeDialog() {
  reset();
  visibleDialog.value = false;
  emit("change-visible", false);
}

/** email消息发送记录保存提交 */
function handleSubmit() {
  if (currentRow.value?.length > 0) {
    emit("change-visible", false, currentRow.value);
  } else {
    return ElMessage.warning("请选择至少一项采集参数");
  }
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;

  emit("change-visible", false);
});

// 获取指定设备的采集参数
const parameterList = ref([]);
const getParameterList = async (id: string) => {
  await request({
    url: "/dmpDosPcm/psmparammonitorrule",
    method: "post",
    data: { equipId: id },
  }).then((res) => {
    parameterList.value = res.data;
    console.log("采集参数", parameterList.value);
  });
};

onMounted(() => {});
// 获取设备类型列表
const laodingTable = ref(false);

const equipTypeList = ref([]);
const getEquipTypeList = async () => {
  await request({
    url: "/iotadmin/scaequipinfo/getTypeListByProcessEquip",
    method: "post",
    data: {
      processEquipId: props.equipId,
    },
  }).then((res) => {
    equipTypeList.value = res.data;
    console.log("设备类型列表", equipTypeList.value);
  });
};

// 改变设备类型
const changeEquipType = (e) => {
  currentRow.value = [];
  if (e) {
    formData.equipTypeId = e;
    search();
  } else {
    formData.equipTypeId = "";
    tableData.value = [];
  }
};
// 搜索
const search = async () => {
  if (!formData.equipTypeId) {
    ElMessage.warning("请先选择设备类型");
  } else {
    laodingTable.value = true;
    await request({
      url: `iotadmin/scaequiptype/get/${formData.equipTypeId}`,
      method: "get",
      data: {},
    })
      .then((res) => {
        tableData.value = res.data.scaEquipCollectionParams;
        laodingTable.value = false;
        console.log("设备采集参数列表", tableData.value);
        breakSingleTableSelect();
      })
      .finally(() => {
        laodingTable.value = false;
      });
  }
};
// 重置
const reset = () => {
  formData.equipTypeId = "";
  tableData.value = [];
};
</script>

<style scoped lang="scss">
:deep(.el-table th .cell) {
  color: black;
  font-weight: 700;
}
.progress {
  color: red;
}
.success {
  color: rgb(100, 207, 86);
}
.formTable3 {
  // :deep(.el-form-item) {
  //   margin: 0 0 13px 0 !important;
  //   width: 100%;
  // }
  :deep(.el-scrollbar__wrap) {
    max-height: 400px;
    overflow-y: auto;
  }
}
</style>
